<template>
  <div class="pager-container" v-if="pageNumber > 1">
    <a @click="handleClick(1)" :class="{disable: current === 1}">|&lt;&lt;</a>
    <a @click="handleClick(current - 1)" :class="{disable: current === 1}">&lt;&lt;</a>
    <a @click="handleClick(n)" v-for="(n, i) in visibleList" :key="i" :class="{active: current === n}">{{ n }}</a>
    <a @click="handleClick(current + 1)" :class="{disable: current === pageNumber}">&gt;&gt;</a>
    <a @click="handleClick(pageNumber)" :class="{disable: current === pageNumber}">&gt;&gt;|</a>
  </div>
</template>

<script>
export default {
  name: "Pager",
  props: {
    // 当前页码
    current: {
      type: Number,
      default: 1
    },
    // 总数据量
    total: {
      type: Number,
      default: 0
    },
    // 页容量
    limit: {
      type: Number,
      default: 10
    },
    // 可见页码数
    visibleNumber: {
      type: Number,
      default: 10
    }
  },
  computed: {
    // 总页数
    pageNumber() {
      return Math.ceil(this.total / this.limit);
    },
    // 可见页码最小值
    visibleMin() {
      let min = this.current - Math.floor(this.visibleNumber / 2);
      if (min < 1) {
        min = 1;
      }
      return min;
    },
    // 可见页码最大值
    visibleMax() {
      let max = this.visibleMin + this.visibleNumber - 1;
      if (max > this.pageNumber) {
        max = this.pageNumber;
      }
      return max;
    },

    visibleList() {
      const list = [];
      for (let i = this.visibleMin; i <= this.visibleMax; i++) {
        list.push(i);
      }
      return list;
    }
  },
  methods: {
    handleClick(newPage) {
      newPage = newPage < 1 ? 1 : newPage;
      newPage = newPage > this.pageNumber ? this.pageNumber : newPage;
      if (newPage === this.current) {
        return;
      }
      this.$emit("pageChange", newPage);
    }
  }
}
</script>

<style scoped lang="less">
@import "~@/styles/var.less";
.pager-container{
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
  a{
    padding: 4px 6px;
    cursor: pointer;
    color: @primary;
    user-select: none;
    &:hover{
      color: @lightWords;
      background-color: @lightBgColor;
    }
    &.disable{
      color: @gray;
      cursor: not-allowed;
    }
    &.active{
      color: @dark;
      font-weight: bold;
      cursor: text;
    }
  }
}
</style>